/**
 * Created by Administrator on 2016/12/29 0029.
 */
var db = require('../../../mymodels/db.js');
var md5 = require('../../../mymodels/md5.js');
var loginfilter = require('../../../filters/loginFilter.js');
var fs = require("fs");
var path = require("path");
var sd = require('silly-datetime');

var multer = require('multer');
var upload = multer({dest: 'uploads/'});
module.exports = ({
    get_index: [loginfilter, function (req, res) {
        //console.log(req.session.uid);
        db.find('posts', {uid: req.session.uid}, {"sort": {date: -1}}, function (err, result) {
            if (err) {
                res.send('出错了' + err);
                return;
            }
            // console.log(result);
            res.render('blog/index', {
                isLogin: req.session.isLogin,
                username: req.session.username,
                lists: result
            });
        })

    }],
    get_login: function (req, res) {
        res.render('blog/login', {
            isLogin: false,
            username: '我的'
        })
    },
    get_register: function (req, res) {
        res.render('blog/register', {
            isLogin: req.session.isLogin,
            username: req.session.username
        })
    },
    get_posts: [loginfilter, function (req, res) {
        res.render("blog/posts", {
            isLogin: req.session.isLogin,
            username: req.session.username
        });
    }],
    get_logout: function (req, res) {
        req.session.isLogin = false;
        req.session.username = '';
        res.render('blog/login', {
            isLogin: false,
            username: '我的'
        })
        // res.redirect('/frontend/blog/login')
        // res.send('退出成功了');
    },
    //获取博客列表.
    get_lists: [loginfilter, function (req, res) {

        db.find('posts', {uid: req.session.uid}, {"sort": {date: -1}}, function (err, result) {
            if (err) {
                res.send('出错了' + err);
                return;
            }
            // console.log(result);
            res.render('blog/lists', {
                isLogin: req.session.isLogin,
                username: req.session.username,
                lists: result
            });
        })

    }],
    //上传文件
    get_upload: [loginfilter, function (req, res) {
        db.find('files',{},{sort:{date:-1}},function (err,result) {
            if(err){
                res.send("查询失败了...");
                return;
            }
            //console.log(result);
            res.render('blog/upload', {
                isLogin: true,
                username: req.session.username,
                files:result
            })
        })

    }],
    ///////////////////////////////////////////////////
    //////////////////////////////////////////////////
    //执行注册用户
    post_doregister: [multer().array(), function (req, res) {
        // console.log(req.body);
        // var obj=req.body;
        var username = req.body.username;
        var psd = req.body.psd;
        db.find("users", {username: username}, function (err, result) {
            if (err) {
                res.send("-5");//服务器错误
                return;
            }
            if (result.length != 0) {
                res.send("-1");//用户名已经被注册了
                return;
            }
            psd = md5(md5(psd) + 'xsd');
            db.insertOne("users", {
                username: username,
                psd: psd
            }, function (err, result) {
                if (err) {
                    res.send("-5");//服务器错误
                    return;
                }
                res.send("1");//注册成功了
            })

        })
    }],
    //执行用户登录
    post_dologin: [multer().array(), function (req, res) {
        //console.log(req.body);
        // var obj=req.body;

        var username = req.body.username;
        var psd = req.body.psd;
        db.find("users", {username: username}, function (err, result) {
            console.log(result[0]._id);
            if (err) {
                res.send("-5");//服务器错误
                return;
            }
            if (result.length == 0) {
                res.send("-1");//该用户还没注册
                return;
            }
            psd = md5(md5(psd) + 'xsd');
            if (psd != result[0].psd) {
                res.send("-2");
                return;
            }
            else {
                req.session['username'] = username;
                req.session['isLogin'] = true;
                req.session.uid = result[0]._id;

                res.send("1");
            }

        })
    }],
    //执行发表博客
    post_doposts: [multer().array(), function (req, res) {
        //console.log(req.body);
        // var obj=req.body;
        var date = new Date();
        /*存储各种时间格式，方便以后扩展*/
        var time = {
            date: date,
            year: date.getFullYear(),
            month: date.getFullYear() + "-" + (date.getMonth() + 1),
            day: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
            minute: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
        }
        var title = req.body.title;
        var tags = req.body.tags;
        var content = req.body.content;

        db.insertOne("posts", {
            title: title,
            uid: req.session.uid,
            author: req.session.username,
            tags: tags,
            content: content,
            readcount: 0,
            commnets: 0,

            date: time
        }, function (err, result) {
            if (err) {
                res.send("-5");
                return;
            }
            res.send("1");
            //console.log(result);
        })

    }],
    //执行上传文件
    post_doupload: [upload.single('file'), function (req, res) {
        var file = req.file;
        var originalname = file.originalname;
        var extname = path.extname(file.originalname);
        var oldpath = file.path;
        var date = sd.format(new Date(), 'YYYYMMDDHHmmss');
        var rand = parseInt(Math.random() * 89999 + 10000);
        var newpath = path.normalize(__dirname + '/../../../uploads/') + date + rand+"_" + originalname;
        fs.rename(oldpath, newpath, function (err) {
            if (err) {
                res.send('上传失败了');
                return;
            }
            /*存储各种时间格式，方便以后扩展*/
            var date = new Date();
            var time = {
                date: date,
                year: date.getFullYear(),
                month: date.getFullYear() + "-" + (date.getMonth() + 1),
                day: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
                minute: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
                date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
            }
            db.insertOne('files',{
                uid:req.session.uid,
                username:req.session.username,
                filename:file.originalname,
                date:time
            },function (err, result) {
                    if(err){
                        res.send('上传失败了');
                        return;
                    }
                    res.redirect('/frontend/blog/upload');
            })
            //res.redirect("上传成功了");
        })
        //  console.log(req.file);
    }]
})